/**
 *
 * @author John Creecy
 */

package battlebarnserver;

import battlebarnserver.entities.PlayerEntity;
import battlebarnserver.util.Conversions;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Iterator;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

public class StateGenerator implements Runnable {

	public void run() {
		calculateState();
	}

	private void calculateState() {
		Iterator it = BattleBarn.actionStack.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry mapEntry = (Map.Entry) it.next();
			PlayerEntity playerActionEntity = (PlayerEntity) mapEntry.getValue();
			BattleBarn.gameState.add(playerActionEntity);
		}
		activityTracker();
	}

	private void activityTracker() {
		if(BattleBarn.packetsIn != BattleBarn.packetsInSnapshot) {
			sendState();
			BattleBarn.packetsInSnapshot = BattleBarn.packetsIn;

			if(BattleBarn.actionStack.size() > BattleBarn.peakUsers) {
				BattleBarn.peakUsers = BattleBarn.actionStack.size();
			}
		} else {
			// no player activity this cycle
			BattleBarn.gameState.clear();
		}
	}

	private void sendState() {
		DatagramPacket sendPacket;
		String outData;
		for (int i = 0; i < BattleBarn.gameState.size(); i++) {
			try {
				Long timeStamp = (long) (System.currentTimeMillis());
				byte[] gameData = new byte[1024];
				DatagramSocket clientSocket = new DatagramSocket();
				PlayerEntity playerEntity = BattleBarn.gameState.get(i);

				String xPad = Conversions.padCoordinate(Integer.toString(Conversions.tileToPixel(playerEntity.getTileX())));
				String yPad = Conversions.padCoordinate(Integer.toString(Conversions.tileToPixel(playerEntity.getTileY())));

				outData = timeStamp + xPad + yPad + playerEntity.getPlayerId();
				gameData = outData.getBytes();

				System.out.println("out: " + outData);
				Iterator it = BattleBarn.clientList.entrySet().iterator();
				while (it.hasNext()) {
					Map.Entry mapEntry = (Map.Entry) it.next();
					InetAddress IPAddress = InetAddress.getByName((String) mapEntry.getKey());
					sendPacket = new DatagramPacket(gameData, gameData.length, IPAddress, 10000);
					clientSocket.send(sendPacket);
					BattleBarn.packetsOut++;
				}
			} catch (IOException ex) {
				Logger.getLogger(StateGenerator.class.getName()).log(Level.SEVERE, null, ex);
			}
		}
		BattleBarn.gameState.clear();
	}
}
